package hflyeer.interceptor;

import hflyeer.pojo.dto.UserDto;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginInterceptor
 *
 * @author hflyeer
 * @date 2021-06-19
 * @describe
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        System.out.println("执行了TestInterceptor的preHandle方法");
        try {
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            UserDto user = (UserDto) request.getSession().getAttribute("USER");
            if (user != null) {
                return true;
            }
            response.sendRedirect(request.getContextPath() + "/index");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
